package service

import (
	"encoding/base64"
	"errors"
	"golang.org/x/crypto/scrypt"
	"log"
	"vpom_-system/global"
	"vpom_-system/model/database"
	"vpom_-system/model/request"
	"vpom_-system/respository"
)

type UserService struct{}

var UserRepository = respository.NewUserRepository()

// Register 注册函数
func (userService *UserService) Register(req request.Register) (error, database.User) {
	// 1.查重 ：就用户名字
	err := UserRepository.Check(global.DB, req.Username)
	if err == nil {
		return errors.New("用户名已存在"), database.User{}

	}
	// 2.判断密码是否相同
	if req.Password != req.Password2 {
		return errors.New("两次密码不相同"), database.User{}
	}
	// 3.对密码进行加密
	hashWord := userService.bcrypt(req.Password)
	// 4.写入结构体
	user := database.User{
		Username: req.Username,
		Password: hashWord,
	}
	// 5.写入数据库
	err = UserRepository.Add(global.DB, user)
	if err != nil {
		return errors.New("写入数据库失败"), database.User{}
	}
	return nil, user
}

// Login 登入函数
func (userService *UserService) Login(req request.Login) (error, database.User) {
	var (
		err  error
		user database.User
	)
	// 1.获取数据库对应信息
	user, err = UserRepository.Find(global.DB, req.Username)
	if err != nil {
		return errors.New("未找到该用户"), database.User{}
	}
	// 2.判断数据是否相同
	hashWord := userService.bcrypt(req.Password)
	if hashWord != user.Password {
		return errors.New("密码错误"), database.User{}
	}
	return nil, user
}

// Bcrypt 密码加密函数
func (userService *UserService) bcrypt(password string) string {
	const Keylen = 10
	salt := make([]byte, 8)
	salt = []byte{12, 32, 4, 66, 66, 22, 222, 11}

	HashPw, err := scrypt.Key([]byte(password), salt, 16384, 8, 1, Keylen)
	if err != nil {
		log.Fatal(err)
	}
	fpw := base64.StdEncoding.EncodeToString(HashPw)
	return fpw
}

// GetUserMsg 获取用户信息，生成token
func (userService *UserService) GetUserMsg(Name string) (database.User, error) {
	user, err := UserRepository.Find(global.DB, Name)
	if err != nil {
		return user, errors.New("未找到用户相关数据")
	}
	return user, nil
}

// UpdateUser 更新用户信息
func (userService *UserService) UpdateUser(user request.ResetPassword) (database.User, error) {
	// 1.检查是否有这个用户
	err := UserRepository.Check(global.DB, user.Username)
	if err != nil {
		return database.User{}, errors.New("未找到用户相关数据")
	}
	// 2.判断原密码是否正确
	user2, _ := userService.GetUserMsg(user.Username)
	if userService.bcrypt(user.OldPassword) != user2.Password {
		return database.User{}, errors.New("原密码输入错误")
	}

	//3. 修改密码
	newUser := database.User{
		Username: user.Username,
		Password: userService.bcrypt(user.NewPassword),
	}
	err = UserRepository.Update(global.DB, newUser)
	if err != nil {
		return newUser, errors.New("更新失败")
	}
	return newUser, nil
}
